from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from cart.views import get_user_id
from django.core.cache import cache
from cart.models import Cart
from cart.serializers import *
from .models import *
from django.db import transaction
import uuid
from alipay import AliPay
from meiduo_admin.settings import *

class BuysInfoView(APIView):
    def post(self,request):
        buy_list = request.data["buys_info"]
        user = get_user_id(request)
        username = user.username+"_goods"
        cache.set(username,buy_list)
        print(cache.get(username))
        return Response({"code":200,"msg":"存入redis成功"})

    def get(self,request):
        user = get_user_id(request)
        username = user.username+"_goods"
        buy_list=cache.get(username)
        try:
            goods = Cart.objects.filter(id__in=buy_list)
            buySER = CartSer(goods,many=True)
            buy_data = buySER.data
            all_money=0
            all_number=0
            for i in buy_data:
                all_money +=i["price"]*i["number"]
                all_number+=i["number"]
            res_data={
                "code":200,
                "msg":"获取数据成功",
                "data":buy_data,
                "all_money":all_money,
                "all_number":all_number
            }
            return Response(data=res_data,status=200)
        except:
            res_data={
                "code":500,
                "msg":"获取数据失败"
            }
            return Response(res_data,status=200)


class OrdersView(APIView):
    def post(self,request):
        all_money = request.data["all_money"]
        pay_method = request.data["pay_method"]
        address = request.data["address"]
        user = get_user_id(request)
        username = user.username+"_goods"
        buys_list = cache.get(username)
        order_name = uuid.uuid4()
        # 乐观锁方法
        try:
            with transaction.atomic():
                save_id = transaction.savepoint()
                orders = Orders(price=all_money, address=address, order_sn=order_name,
                                pay_method=pay_method, user_id=user)
                while True:
                    carts = Cart.objects.filter(id__in=buys_list)
                    for i in carts:
                        buy_number = i.number
                        goods = Goods.objects.get(id__in=buys_list)
                        kucun_number = goods.number
                        if buy_number>kucun_number:
                            data={
                                "code":508,
                                "msg":"老子没货"
                            }
                            return Response(data)
                        else:
                            new_kucun_number = kucun_number-buy_number
                            res = Goods.objects.filter(id=i.goods_id.id,number=kucun_number).update(number=new_kucun_number)
                            if res == 0:
                                continue
                            else:
                               Cart.objects.filter(id=i.id).delete()
                               cache.delete(username)
                               break
                    orders.save()
                    transaction.savepoint_commit(save_id)
                    return Response({"code": 200})
        except:
            transaction.savepoint_rollback(save_id)
            return Response({"code":500})

        # 悲观锁方法
        # try:
        #     with transaction.atomic():
        #         save_id = transaction.savepoint()
        #         orders = Orders(price=all_money,address=address,order_sn=order_name,
        #                         pay_method=pay_method,user_id=user)
        #         try:
        #             cart = Cart.objects.filter(id__in=buys_list)
        #             for i in cart:
        #                 buy_number = i.number
        #                 goods = Goods.objects.select_for_update().get(id=i.goods.id.id)
        #                 if buy_number > goods.number:
        #                     data={
        #                         "code":505,
        #                         "msg":"没有给你的"
        #                     }
        #                     return Response(data,status=200)
        #                 else:
        #                     goods.number -= buy_number
        #                     goods.save()
        #                     Cart.objects.filter(id=i.id).delete()
        #                     cache.delete(username)
        #             orders.save()
        #             transaction.savepoint_rollback(save_id)
        #             data={
        #                 "code":200,
        #                 "msg":"订单完成"
        #             }
        #             return Response(data,status=200)
        #         except Exception as e:
        #             transaction.savepoint_rollback(save_id)
        #             return Response({"code":8000})
        # except:
        #     data={
        #         "code":500,
        #         "msg":"失败"
        #     }
        #     return Response(data,status=200)


class alipayView(APIView):
    def get(self,request):
        order_id = request.query_params["order_id"]
        all_money = request.query_params["all_money"]
        alipay = AliPay(
            appid=Alipay_ID,
            app_notify_url="http://www.baidu.com", #回调路由
            app_private_key_string=MEIDUOKEY,
            alipay_public_key_string=ALIKEY,
            sign_type="RSA",
            debug=False
        )
        subject = "美多商城订单"
        order_string = alipay.api_alipay_trade_page_pay(
            out_trade_no=order_id,
            total_amount=alipayView,
            subject=subject,
            return_url="http://www.baidu.com",
        )
        request_url = "http://openapi.alipaydev.com/gateway.do?" + order_string
        data={
            "code":200,
            "data":request_url
        }
        return Response(data,status=200)